<template>
  <div class="flow-container">
    <!-- 工具栏 -->
    <div v-if="!readOnly" style="text-align: right;">
      <div class="quickbar">
        <el-button type="warning" icon="el-icon-video-play" size="mini" round @click="tmpSaveInfo">
          暂存
        </el-button>
        <el-button type="primary" icon="el-icon-check" size="mini" round @click="submitInfo">
          提交
        </el-button>
        <el-button type="danger" icon="el-icon-close" size="mini" round @click="discard">
          废弃
        </el-button>
      </div>
    </div>

    <div v-else style="text-align: right;">
      <div class="quickbar">
        <el-button type="info" size="mini">
          <router-link :to="'/publishDeploy?flowId=' + form.id">
            查看部署
          </router-link>
        </el-button>
        <el-button
          v-if="form.processerId && user.id===form.processerId && (form.flowNodeId===FLOW_TEST || form.flowNodeId===FLOW_RC_DP || form.flowNodeId===FLOW_PROD_DP)"
          type="warning"
          :loading="quickDeployLoading"
          icon="el-icon-video-play"
          size="mini"
          round
          @click="deploy"
        >
          快速部署
        </el-button>
      </div>
    </div>

    <el-row>
      <el-col :span="24">
        <div v-if="form.title" class="normal-title flow-title">
          {{ form.title }}
        </div>
        <div v-else class="normal-title flow-title">
          服务器发布申请
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-descriptions title="申请人信息" :column="3" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user" />
              申请人
            </template>
            {{ form.applierName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline" />
              岗位
            </template>
            {{ form.jobName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone" />
              申请时间
            </template>
            {{ form.createTime ? form.createTime.toLocaleString() : '' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets" />
              流程编号
            </template>
            {{ form.flowNo }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets" />
              发布类型
            </template>
            <el-select v-model="form.publishType" :disabled="readOnly" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.publish_type"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-descriptions-item>
        </el-descriptions>

        <div style="margin-top: 15px;">
          <div class="el-descriptions__header">
            <div class="el-descriptions__title">
              发布项目
            </div>
            <div class="el-descriptions__extra">
              <el-button
                v-if="!readOnly"
                class="filter-item"
                size="mini"
                style="float: right;padding: 4px 10px"
                type="primary"
                icon="el-icon-plus"
                @click="onAddProject"
              >
                新增项目
              </el-button>
            </div>
          </div>
          <el-table ref="projectListTable" :data="publishProjectList" style="width: 100%;">
            <el-table-column prop="name" label="项目" width="300">
              <template slot-scope="scope">
                {{ projectMap[scope.row.projectId] }}
              </template>
            </el-table-column>
            <el-table-column prop="branch" label="分支" />
            <el-table-column prop="version" label="版本号" width="150" />
            <el-table-column prop="gray" label="发布方式" width="150">
              <template slot-scope="scope">
                {{ dict.label.gray_type[scope.row.gray] }}
              </template>
            </el-table-column>
            <el-table-column prop="replicas" label="实例数量" width="150" />
            <el-table-column prop="grayReplicas" label="灰度数量" width="150" />
            <el-table-column prop="resourceId" label="规格" width="150">
              <template slot-scope="scope">
                {{ resourceMap[scope.row.resourceId] }}
              </template>
            </el-table-column>
            <el-table-column v-if="!readOnly" label="操作" fixed="right" align="center" width="200">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="toDeleteProject(scope.row)"
                />
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="toEditProject(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-descriptions style="margin-top: 15px;" title="配置变更" :column="3" border>
          <el-descriptions-item style="width: 30%;">
            <template slot="label">
              <i class="el-icon-time" />
              发布时间
            </template>
            <el-date-picker v-model="form.publishTime" :disabled="readOnly" type="datetime" style="width: 370px;" />
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-postcard" />
              DB变动
            </template>
            <el-radio-group v-model="form.dbChanged" :disabled="readOnly" size="mini">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-receiving" />
              缓存变动
            </template>
            <el-radio-group v-model="form.cacheChanged" :disabled="readOnly" size="mini">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions style="margin-top: 15px;" direction="vertical" title="脚本内容" :column="1" border>
          <el-descriptions-item v-if="form.dbChanged===COMMON_CHANGED">
            <template slot="label">
              DB脚本
            </template>
            <el-input v-model="form.dbScript" :readonly="readOnly" :rows="5" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
          <el-descriptions-item v-if="form.dbChanged===COMMON_CHANGED">
            <template slot="label">
              回滚脚本
            </template>
            <el-input v-model="form.rollbackDbScript" :readonly="readOnly" :rows="5" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
          <el-descriptions-item v-if="form.cacheChanged===COMMON_CHANGED">
            <template slot="label">
              缓存大小及建议
            </template>
            <el-input v-model="form.cacheScript" :readonly="readOnly" :rows="5" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              统配
            </template>
            <el-input v-model="form.configserverScript" :readonly="readOnly" :rows="5" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              风险评估
            </template>
            <el-input v-model="form.riskAssessment" :readonly="readOnly" :rows="3" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions style="margin-top: 15px;" title="流程人员" :column="4" border>
          <el-descriptions-item>
            <template slot="label">
              测试介入
            </template>
            <el-radio-group v-model="form.hasTester" :disabled="readOnly" size="mini" @change="hasTesterChange">
              <el-radio :label="NO_TESTER">否</el-radio>
              <el-radio :label="HAS_TESTER">是</el-radio>
            </el-radio-group>
          </el-descriptions-item>
          <el-descriptions-item v-if="form.hasTester===COMMON_CHANGED">
            <template slot="label">
              测试人员
            </template>
            <el-select v-model="form.testerId" :disabled="readOnly" filterable placeholder="请选择测试人员">
              <el-option
                v-for="item in testerList"
                :key="item.id"
                :label="`${item.nickName} (${item.jobName})`"
                :value="item.id"
              />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              运维人员
            </template>
            <el-select v-model="form.deployerId" :disabled="readOnly" filterable placeholder="请选择">
              <el-option
                v-for="item in deployerList"
                :key="item.id"
                :label="`${item.nickName} (${item.jobName})`"
                :value="item.id"
              />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              开发经理
            </template>
            <el-select v-model="form.managerId" :disabled="readOnly" filterable placeholder="请选择">
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="`${item.nickName} (${item.jobName})`"
                :value="item.id"
              />
            </el-select>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions style="margin-top: 15px;" :label-style="{display: 'none'}" :content-style="{border: '0px'}" direction="vertical" title="备注" :column="1" border>
          <el-descriptions-item>
            <el-input v-model="form.remarks" :readonly="readOnly" :rows="3" type="textarea" style="width: 100%;" />
          </el-descriptions-item>
        </el-descriptions>

      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <!-- 审批记录 -->
        <div v-if="showApprovalArea" style="margin-top: 25px;">
          <span style="font-size: 18px;font-weight: bold;">
            流程处理
          </span>
          <el-divider />
          <el-table ref="approvalTable" :data="approvalData" border size="small" style="width: 100%;">
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="flowNodeName" label="节点名称" />
            <el-table-column prop="operator" label="操作人姓名" />
            <el-table-column prop="handle" label="操作">
              <template slot-scope="scope">
                {{ dict.label.approval_handle[`${scope.row.handle}`] }}
              </template>
            </el-table-column>
            <el-table-column prop="opinions" label="意见" />
          </el-table>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <!-- 审批意见 -->
        <div v-if="showApprovalOperation" style="margin-top: 25px;">
          <span style="font-size: 18px;font-weight: bold;">
            审批意见
          </span>
          <el-divider />

          <div style="margin-bottom: 5px;">
            <el-select v-model="formAppv.handle" placeholder="请选择" @change="handleChange">
              <el-option key="1" label="通过" :value="APPROVED" />
              <el-option key="2" label="驳回" :value="REJECT" />
              <el-option key="4" label="转发" :value="Forward" />
            </el-select>
            <el-select v-model="formAppv.forwardTo" :disabled="forwardToReadOnly" filterable placeholder="请选择">
              <el-option
                v-for="item in forwardToList"
                :key="item.id"
                :label="`${item.nickName} (${item.jobName})`"
                :value="item.id"
              />
            </el-select>
            <el-button type="primary" icon="el-icon-check" size="mini" round @click="submitApproval">
              提交
            </el-button>
          </div>
          <el-form ref="formAppv" :model="formAppv" :rules="ruleAppv" size="small" label-width="0px">
            <el-form-item label="">
              <el-input v-model="formAppv.opinions" type="textarea" :rows="10" style="width: 100%" />
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-dialog :close-on-click-modal="false" :visible.sync="projectInfoDlgVisible" :title="projectInfoDlgTitle" width="500px">
      <div class="content">
        <el-form ref="projectInfoDlgForm" :model="projectInfoDlgForm" :rules="projectInfoDlgFormRules" size="small" label-width="80px">
          <el-form-item label="服务名称" prop="id">
            <el-select v-model="projectInfoDlgForm.projectId" filterable placeholder="请选择发布服务" style="width: 375px;" @change="onProjectSelectChange">
              <el-option
                v-for="item in projectList"
                :key="item.projectId"
                :label="item.dpServer.name"
                :value="Number(item.dpServer.projectId)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部署分支" prop="branch">
            <el-select v-model="projectInfoDlgForm.branch" filterable style="width: 375px;" @change="onProjectBranchSelectChange">
              <el-option
                v-for="item in projectInfoBranchList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
            <div v-if="projectInfoBranchCommitMessage" class="project-commit">
              最新提交:{{ projectInfoBranchCommitMessage }}
            </div>
          </el-form-item>
          <el-form-item label="版本" prop="version">
            <el-input v-model="projectInfoDlgForm.version" style="width: 375px;" />
          </el-form-item>
          <el-form-item label="是否灰度" prop="gray">
            <el-radio-group v-model="projectInfoDlgForm.gray" size="mini">
              <el-radio label="0">全发</el-radio>
              <el-radio label="1">灰度</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="节点数量" prop="replicas">
            <el-input-number v-model="projectInfoDlgForm.replicas" size="mini" />
          </el-form-item>
          <el-form-item v-if="projectInfoDlgForm.gray===GRAY_TYPE_GRAY" label="灰度数量" prop="grayReplicas">
            <el-input-number v-model="projectInfoDlgForm.grayReplicas" size="mini" />
          </el-form-item>
          <el-form-item label="资源规格" prop="resourceId">
            <el-select v-model="projectInfoDlgForm.resourceId" filterable placeholder="请选择" style="width: 375px;">
              <el-option
                v-for="item in resourceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="projectInfoDlgVisible=false">取消</el-button>
        <el-button type="primary" @click="onProjectDlgConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudPublishSheetFlow, { getFlowNodeById } from '@/api/deploy/publishSheetFlow'
import crudPublishSheetApprovalRecord, { findByPublishSheetId } from '@/api/deploy/publishSheetApprovalRecord'
import { mapGetters } from 'vuex'
import _ from 'lodash'
import global_const from '@/mixins/global_const'
import * as APIS from '@/api/server/index'
import { queryUserByRoleId, queryAll } from '@/api/system/user'
import { Notification } from 'element-ui'

const defaultProjectForm = {
  projectId: null,
  branch: '',
  version: '',
  gray: '0',
  replicas: null,
  grayReplicas: null,
  resourceId: null
}

export default {
  name: 'FlowForm',
  components: {},
  dicts: ['gray_type', 'publish_type', 'approval_handle'],
  mixins: [global_const],
  data() {
    return {
      projectInfoBranchListLoading: false,
      projectInfoBranchList: [],
      projectInfoBranchCommitMessage: '',
      projectInfoDlgVisible: false,
      projectInfoDlgStatus: 'add',
      projectInfoDlgForm: {},
      projectInfoDlgFormRules: {
        projectId: [
          { required: true, message: '项目不能为空', trigger: 'blur' }
        ],
        branch: [
          { required: true, message: '部署分支不能为空', trigger: 'blur' }
        ],
        version: [
          { required: true, message: '版本号不能为空', trigger: 'blur' }
        ],
        replicas: [
          { required: true, message: '部署实例数量不能为空', trigger: 'blur' }
        ],
        resourceId: [
          { required: true, message: '服务器规格不能为空', trigger: 'blur' }
        ]
      },

      publishProjectList: [],

      quickDeployLoading: false,

      publishId: -1,
      permission: {
        add: ['admin', 'publishSheetFlow:add'],
        edit: ['admin', 'publishSheetFlow:edit'],
        del: ['admin', 'publishSheetFlow:del']
      },

      form: {},
      formAppv: { id: null, publishSheetFlowId: null, flowNodeId: null, flowNodeName: null, operatorId: null, handle: 1, opinions: '同意', forwardTo: null },

      testerList: [],
      managerList: [],
      deployerList: [],
      forwardToList: [],
      forwardToReadOnly: true,

      approvalData: [],

      ruleAppv: { },

      defaultForm: {
        id: null,
        title: null,
        flowNo: null,
        publishTime: null,
        applierId: null,
        publishType: this.GRAY_TYPE_ALL,
        dbChanged: this.COMMON_NO_CHANGED,
        cacheChanged: this.COMMON_NO_CHANGED,
        riskAssessment: null,
        dbScript: null,
        rollbackDbScript: null,
        configserverScript: null,
        remarks: null,
        hasTester: '0',
        testerId: null,
        deployerId: null,
        managerId: null,
        createTime: null,
        endTime: null,
        flowNodeId: null,
        processerId: null,
        flowStatus: null,
        isDraft: true
      }
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'projectList',
      'projectMap',
      'resourceList',
      'resourceMap'
    ]),
    projectInfoDlgTitle() {
      if (this.projectInfoDlgStatus === 'add') {
        return '新增服务'
      }
      return '编辑服务'
    },
    readOnly() {
      // 控制申请单只读
      const nodeId = this.form.flowNodeId
      if (nodeId || nodeId === this.FLOW_STATUS_DRAFT) {
        const flowStatus = this.form.flowStatus
        if (flowStatus === this.FLOW_STATUS_PROCESS || flowStatus === this.FLOW_STATUS_FINISH || flowStatus === this.FLOW_STATUS_DISCARD) {
          return true
        }

        // 当前用户=processId才允许操作
        if (this.form.processerId && this.user.id !== this.form.processerId) {
          return true
        }
      }
      return false
    },
    showApprovalArea() {
      // 新建情况
      if (this.publishId == null || this.publishId === -1) {
        return false
      }
      // 如果是驳回转态，那么可以看到审批历史
      if (this.form.flowStatus === this.FLOW_STATUS_REJECT) {
        return true
      }
      // 非草稿状态就显示
      return this.form.flowNodeId > this.FLOW_DRAFT
    },
    showApprovalOperation() {
      // 显示审批意见 1-进行中 3.驳回 processId=userId
      if (this.form.flowStatus === this.FLOW_STATUS_PROCESS) {
        return this.user.id === this.form.processerId
      }
      return false
    }
  },
  created() {
    const query = this.$route.query
    if (query === undefined || query.publishId === undefined) {
      return
    }
    this.initUserList()
    this.publishId = parseInt(query.publishId)
  },
  mounted() {
    if (this.publishId == null || this.publishId === -1) {
      this.initFlowForm()
      return
    }
    findByPublishSheetId(this.publishId).then(data => {
      this.approvalData = data
    })
    crudPublishSheetFlow.findById(this.publishId).then(res => {
      this.form = res

      // 相关字段转成字符串
      this.form.cacheChanged = `${this.form.cacheChanged}`
      this.form.dbChanged = `${this.form.dbChanged}`
      this.form.hasTester = `${this.form.hasTester}`
      this.form.publishType = `${this.form.publishType}`

      this.publishProjectList = this.form.publishProjects

      this.formAppv.publishSheetFlowId = this.form.id
      this.formAppv.flowNodeId = this.form.flowNodeId
      getFlowNodeById(this.formAppv.flowNodeId).then(res => {
        this.formAppv.flowNodeName = res.name
      })
      this.formAppv.operatorId = this.form.processerId
      this.formAppv.operator = this.user.nickName
    })
  },
  methods: {
    handleChange(data) {
      // 转发
      if (data === 4) {
        this.forwardToReadOnly = false
        this.formAppv.opinions = '转发'
      } else {
        this.formAppv.forwardTo = null
        this.forwardToReadOnly = true
        this.formAppv.opinions = '同意'
      }
    },
    initFlowForm() {
      // 初始表单
      // 获取部门信息和岗位信息
      const jobName = this.user.jobs.length > 0 ? this.user.jobs[0].name : '未知岗位'
      this.form = _.clone(this.defaultForm)
      this.form['jobName'] = jobName
      this.form.applierId = this.user.id
      this.form['applierName'] = this.user.nickName
      this.form.createTime = new Date()
      this.form.dbChanged = this.COMMON_NO_CHANGED
      this.form.cacheChanged = this.COMMON_NO_CHANGED
      this.form.publishType = this.GRAY_TYPE_ALL

      crudPublishSheetFlow.getPublishSheetNo().then(res => {
        this.form.flowNo = res
      })
    },
    hasTesterChange() {
      if (this.form.hasTester === 0) {
        this.form.testerId = null
      }
    },
    initUserList() {
      queryUserByRoleId(this.ROLE_TESTER_ID).then(data => {
        this.initJobName(data)
        this.testerList = data
      })
      queryAll().then(data => {
        this.initJobName(data)
        this.forwardToList = data
      })
      queryUserByRoleId(this.ROLE_MANAGER_ID).then(data => {
        this.initJobName(data)
        this.managerList = data
      })
      queryUserByRoleId(this.ROLE_DEPLOYER_ID).then(data => {
        this.initJobName(data)
        this.deployerList = data
      })
    },
    initJobName(userList) {
      userList.forEach(user => {
        const jobName = user.jobs.length > 0 ? user.jobs[0].name : ''
        user['jobName'] = jobName
      })
    },
    validForm() {
      if (this.publishProjectList.length === 0) {
        this.$notify({
          title: '请添加要服务的项目',
          type: 'error',
          duration: 1500
        })
        return false
      }
      // 发布时间
      if (!this.form.publishTime) {
        this.$notify({
          title: '请选择要发布的时间',
          type: 'error',
          duration: 1500
        })
        return false
      }
      // 测试介入-测试人员
      if (this.form.hasTester === this.HAS_TESTER && !this.form.testerId) {
        this.$notify({
          title: '请选择测试人员',
          type: 'error',
          duration: 1500
        })
        return false
      }
      // 运维人员
      if (!this.form.deployerId) {
        this.$notify({
          title: '请选择运维人员',
          type: 'error',
          duration: 1500
        })
        return false
      }

      // 开发经理
      if (!this.form.managerId) {
        this.$notify({
          title: '请选择开发经理',
          type: 'error',
          duration: 1500
        })
        return false
      }
      return true
    },
    initDraftForm() {
      if (!this.form.title) {
        // 发布申请-某某人
        const title = `${this.user.nickName}发布申请`
        this.form.title = title
      }

      if (this.form['flowStatus'] == null || this.form['flowStatus'] === undefined) {
        this.form['flowStatus'] = this.FLOW_STATUS_DRAFT
      }

      if (this.form['flowNodeId'] == null || this.form['flowNodeId'] === undefined) {
        this.form['flowNodeId'] = this.FLOW_DRAFT
      }
    },
    save(isDraft, callback) {
      if (this.validForm()) {
        this.form['publishProjects'] = this.publishProjectList
        this.form['isDraft'] = isDraft

        this.initDraftForm()
        this.saveForm(callback)
      }
    },
    saveForm(callback) {
      this.saveLoading = true
      crudPublishSheetFlow.add(this.form).then(data => {
        this.form = data
        this.editSuccessNotify()
        if (callback) {
          callback()
        }
      }).catch(() => {
      }).finally(() => {
        this.saveLoading = false
      })
    },
    // 暂存
    tmpSaveInfo() {
      this.save(true)
    },
    // 提交
    submitInfo() {
      this.save(false, () => {
        this.backToList()
      })
    },
    // 废弃
    discard() {
      const _this = this
      this.$confirm(`确认废弃该项目?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.form['flowStatus'] = _this.FLOW_STATUS_DISCARD
        _this.form['flowNodeId'] = _this.FLOW_FINISH
        _this.form['isDraft'] = false
        if (_this.form.id) {
          _this.saveForm(() => {
            _this.backToList()
          })
        } else {
          _this.backToList()
        }
      }).catch(() => {})
    },
    submitApproval() {
      this.$refs['formAppv'].validate((valid) => {
        if (valid) {
          crudPublishSheetApprovalRecord.add(this.formAppv).then(() => {
            this.editSuccessNotify()
            this.$bus.$emit('global-approval-change')
          }).catch(() => {
            this.saveLoading = false
          })
          this.backToList()
        }
      })
    },
    backToList() {
      this.$router.push('/deploy/publish/index')
    },
    editSuccessNotify() {
      this.$notify({
        title: '编辑成功',
        type: 'success',
        duration: 2500
      })
    },

    toDeleteProject(project) {
      const index = _.findIndex(this.publishProjectList, {
        projectId: project.projectId
      })
      const _this = this
      this.$confirm(`确认删除项目?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.publishProjectList.splice(index, 1)
      }).catch(() => {})
    },
    toEditProject(project) {
      // 重新拉取分支列表
      this.getBranchList(project.projectId)

      this.projectInfoDlgVisible = true
      this.projectInfoDlgStatus = 'edit'
      this.projectInfoDlgForm = _.clone(project)
    },
    onAddProject() {
      this.projectInfoDlgVisible = true
      this.projectInfoDlgStatus = 'add'
      this.projectInfoDlgForm = _.clone(defaultProjectForm)
    },
    onProjectDlgConfirm() {
      this.$refs.projectInfoDlgForm.validate(valid => {
        if (valid) {
          if (this.projectInfoDlgForm.replicas === 0) {
            this.$notify({
              title: '实例节点数量不能为0',
              type: 'error',
              duration: 1500
            })
            return
          }

          if (this.projectInfoDlgForm.gray === this.GRAY_TYPE_GRAY) {
            const grayReplicas = this.projectInfoDlgForm.grayReplicas
            if (grayReplicas > this.projectInfoDlgForm.replicas) {
              this.$notify({
                title: '实例节点灰度数量不能大于节点数量',
                type: 'error',
                duration: 1500
              })
              return
            }
          }

          const index = _.findIndex(this.publishProjectList, {
            projectId: this.projectInfoDlgForm.projectId
          })
          if (this.projectInfoDlgStatus === 'add') {
            if (index > -1) {
              this.$notify({
                title: '该项目已经在列表中，无法添加',
                type: 'error',
                duration: 1500
              })
              return
            }
            this.publishProjectList.push(_.clone(this.projectInfoDlgForm))
          } else {
            if (index === -1) {
              this.$notify({
                title: '该项目已经不在列表中，无法修改',
                type: 'error',
                duration: 1500
              })
              return
            }

            this.publishProjectList.splice(index, 1, _.clone(this.projectInfoDlgForm))
          }
          this.projectInfoDlgVisible = false
          this.projectInfoBranchCommitMessage = null
          this.$refs.projectInfoDlgForm.resetFields()
        }
      })
    },
    onProjectSelectChange(projectId) {
      this.projectInfoDlgForm.branch = 'master'
      this.getBranchList(projectId)
    },
    getBranchList(projectId) {
      this.projectInfoBranchListLoading = true
      return APIS.getProjectBranchList({
        projectId: projectId
      }).then(res => {
        this.projectInfoBranchList = res
      }).finally(() => {
        this.projectInfoBranchListLoading = false
      })
    },
    onProjectBranchSelectChange(branchName) {
      const index = _.findIndex(this.projectInfoBranchList, {
        name: branchName
      })
      if (index >= 0) {
        const branchItem = this.projectInfoBranchList[index]
        this.projectInfoBranchCommitMessage = branchItem.commit.message
      }
    },

    deploy() {
      this.quickDeployLoading = true
      crudPublishSheetFlow.deployFlow(this.publishId).then(() => {
        Notification.success({ title: '部署成功', duration: 1000 })
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.quickDeployLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>

  .flow-container {
    padding: 0px 120px 50px 120px;
  }

  .quickbar {
    height: 48px;
    background: transparent;
    border-bottom: 1px;
    padding: 10px;
    line-height: 48px;
  }

  .flow-title {
    margin: 25px 5px;
    font-size: 25px;
    font-weight: bold;
  }

  .normal-title {
    text-align: center;
    vertical-align: middle;
  }

  .project-commit {
    color: grey;
    font-size: 12px;
  }

  ::v-deep .el-descriptions__header {
    margin-bottom: 5px !important;
  }

  ::v-deep .el-divider--horizontal {
    margin-top: 5px !important;
  }
</style>
